<template>
  <div>
    <FormMode :mode="formMode?.mode">
      <mci-form ref="autoFormRef" :model="autoForm" :rules="rules" label-width="auto" label-position="top">
        <!-- 处理类型 -->
        <div class="flex gap-40">
          <mci-form-item label="处理类型" prop="cfgType">
            <mci-radio-group
              v-model="autoForm.cfgType"
              :disabled="formMode?.mode === 'view'"
              :direction="'row'"
              :options="[
                {
                  text: '新增记录',
                  label: ACTION_TYPE.INSERT
                },
                {
                  text: '更新记录',
                  label: ACTION_TYPE.UPDATE
                }
              ]"
            />
          </mci-form-item>
        </div>
        <!-- 数据集 -->
        <mci-form-item label="数据集" prop="tableName">
          <mci-select v-model="autoForm.tableName" :list="tableOptions" placeholder="请选择" style="width: 100%" />
        </mci-form-item>
        <!-- 修改条件 -->
        <div v-if="autoForm.cfgType === ACTION_TYPE.UPDATE">
          <mci-form-item label="更新记录key" prop="conditions">
            <Conditions
              ref="conditionsRef"
              v-model="autoForm.conditions"
              :variable-options="variableOptions"
              class="w-full"
              :left-options="conditionOptions"
              @on-update:data="handleUpdateConditions"
            />
          </mci-form-item>
        </div>
        <div v-if="autoForm.tableName">
          <mci-form-item label="字段映射" prop="mapping">
            <FieldMapping
              ref="fieldMappingRef"
              :column-options="columnOptions"
              :variable-options="variableOptions"
              :mapping="autoForm.mapping"
              :is-match="mappingData.isMatch"
              @change="handleChange"
              @match="mappingData.isMatch = false"
            />
          </mci-form-item>
        </div>
      </mci-form>
    </FormMode>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue';
import { MciRadioGroup, MciForm, MciFormItem, MciSelect } from '@/components/base';
import { FormMode } from '@/components/base/Form/mode';
import type { AutoForm } from './data';
import { ACTION_TYPE } from './data';

import { getTableList, getTableFields } from '@/api/decision-engine';
import type { IGetTableListRes, IGetTableFieldsReq, IGetTableFieldsRes } from '@/api/decision-engine';
import { Conditions } from '@/components/business/Conditions';
import FieldMapping from '@/components/business/FieldMapping/index.vue';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useFormMode } from '@/components/base/Form/mode';
import { useDictStore } from '@/store/dict';

const currentNode = useCurrentNode();
const dictStore = useDictStore();
const oldData = currentNode.getAutomaticData();

const formMode = useFormMode();

// 映射字段
const fieldMappingRef = ref<any>();
// const tableFlag = ref(false);
const mappingData = reactive({
  isMatch: false
});
// 表单
const autoFormRef = ref<any>();
const autoForm = reactive<AutoForm>({
  cfgType: oldData && oldData.cfgType ? oldData.cfgType : ACTION_TYPE.INSERT,
  tableName: oldData && oldData.tableName ? oldData.tableName : '',
  mapping: oldData && oldData.mapping ? oldData.mapping : {},
  conditions: oldData && oldData.conditions ? oldData.conditions : {}
});
// 表选项
const tableOptions = ref<any[]>([]);
// 列选项
const columnOptions = ref<any[]>([]);
// 表
const tableRequest = async () => {
  const data: IGetTableListRes = await getTableList();

  if (data) {
    tableOptions.value = data.map((item: string) => {
      return {
        label: item,
        value: item
      };
    });
    if (autoForm.tableName) {
      columnRequest();
    }
  } else {
    tableOptions.value = [];
  }
};
tableRequest();
// 列
const columnRequest = async () => {
  if (!autoForm.tableName) return;
  const params: IGetTableFieldsReq = {
    tableName: autoForm.tableName
  };
  const data: IGetTableFieldsRes = await getTableFields(params);
  columnOptions.value = data || [];

  // if (tableFlag.value) {
  //   mappingData.isMatch = true;
  //   tableFlag.value = false;
  // } else {
  //   fieldMappingRef.value?.buildRowData(autoForm.mapping);
  // }
  fieldMappingRef.value?.buildRowData(autoForm.mapping);
  buildConditionOptions(columnOptions.value);
};

// 条件
// 选项
const conditionOptions = ref<any[]>([]);
// 变量选项
const variableOptions = computed(() => {
  return dictStore.systemVarsOptions.concat(currentNode.currentAndParentPrivateVariablesOptions.value.concat(currentNode.currentAndParentNodeVariablesOptions.value));
});

// 条件校验
const validateConditions = (rule: any, value: any, callback: any) => {
  if (autoForm.conditions && autoForm.conditions.conditions && autoForm.conditions.conditions.length) {
    callback();
  } else {
    callback(new Error('请添加修改条件'));
  }
};
// 表单校验-更新记录key
const mappingValidator = (rule: any, value: string, callback: any) => {
  if (!value) {
    return callback(new Error('请添加更新记录key'));
  }
  const keys = Object.keys(value);
  if (!keys || !keys.length) {
    return callback(new Error('请添加更新记录key'));
  }
  callback();
};
const rules = reactive<any>({
  cfgType: [{ required: true, message: '请填写处理类型', trigger: 'blur' }],
  tableName: [{ required: true, message: '请选择数据集', trigger: 'blur' }],
  conditions: [{ required: true, validator: validateConditions, trigger: 'blur' }],
  mapping: [{ required: true, validator: mappingValidator, trigger: 'blur' }]
});

// 节点数据变化
const handleChange = (val: any) => {
  autoForm.mapping = val;
};

const buildConditionOptions = (data: any[]) => {
  if (!data) conditionOptions.value = [];
  conditionOptions.value = data.map((item: any) => {
    return {
      label: item.varLabel ? item.varLabel : item.varName,
      value: item.varName
    };
  });
};

// 条件变化回调
const handleUpdateConditions = (val: any) => {
  autoForm.conditions = val;
};

watch(
  [() => autoForm.tableName/** , () => autoForm.cfgType*/],
  ([newTableName], [oldTableName]) => {
    // 表名
    if (newTableName && newTableName !== oldTableName) {
      autoForm.conditions = {};
      autoForm.mapping = {};
      // tableFlag.value = true;
      columnRequest();
    }
    // // 条件
    // if (cfgType !== oldCfgType && cfgType === ACTION_TYPE.INSERT) {
    //   autoForm.conditions = {};
    // }
  },
  { deep: true }
);
watch(
  [() => autoForm],
  () => {
    currentNode.saveAutomaticData(autoForm);
  },
  { deep: true }
);
</script>
